package com.ruoyi.file.service;

import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.system.api.domain.SysFileAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
public class AgentFileServiceImpl implements AgentFileService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有文件信息
     */
    public List<SysFileAgent> getFileList() {
        String sql = "SELECT id, name, type, url, create_time " +
                "FROM agent_file " +
                "ORDER BY create_time DESC";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(SysFileAgent.class));
    }
    @Override
    public String uploadFile(MultipartFile file,String filePath) {
        try {


            // 提取文件类型
            String fileType = extractFileType(file.getOriginalFilename());

            // 保存文件信息到数据库（SQL直接写在Service中）
            saveFileInfoToDb(file.getOriginalFilename(), fileType, filePath);

            return filePath;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }



    private String extractFileType(String fileName) {
        if (fileName == null) return "";
        int lastIndex = fileName.lastIndexOf('.');
        return lastIndex >= 0 ? fileName.substring(lastIndex + 1).toLowerCase() : "";
    }

    private void saveFileInfoToDb(String fileName, String fileType, String filePath) {
        // 手动构建SQL插入语句
        String sql = "INSERT INTO agent_file (id, name, type, url, create_time) " +
                "VALUES (?, ?, ?, ?, NOW())";

        // 生成UUID
        String uuid = UUID.randomUUID().toString();

        // 执行SQL
        jdbcTemplate.update(sql, uuid, fileName, fileType, filePath);
    }
}
